package cn.edu.ujn.finaltest.controller;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.ujn.finaltest.dao.Customer;
import cn.edu.ujn.finaltest.dao.Product;
import cn.edu.ujn.finaltest.dao.User;
import cn.edu.ujn.finaltest.service.IProductService;
import cn.edu.ujn.finaltest.util.Page;

@Controller
public class ProductController {
	@Autowired
	private IProductService productService;

	@RequestMapping(value = "/product/list.action")
	public String list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows,
			Integer id, String name, Integer price, Model model) {
		Page<Product> findProductlist = productService.findProductList(page, rows, id, name, price);
		model.addAttribute("page", findProductlist);
		model.addAttribute("id", id);
		model.addAttribute("name", name);
		model.addAttribute("price", price);
		return "product";
	}

	@RequestMapping(value = "/product/create.action")
	@ResponseBody
	public String productCreate(Product product,Integer id,String name,Integer price, HttpSession session) {
		// 获取Session中的当前用户信息
		User user = (User) session.getAttribute("USER_SESSION");
		// 将当前用户id存储在客户对象中
		//product.setId(user.getUser_id());
        product.setId(id);
        product.setName(name);
        product.setPrice(price);
		// 执行Service层中的创建方法，返回的是受影响的行数
		int rows = productService.insertSelective(product);
		if (rows > 0) {
			return "OK";
		} else {
			return "FAIL";
		}
	}
	
	/**
	 * 通过id获取客户信息
	 */
	@RequestMapping("/product/getProductById.action")
	@ResponseBody
	public Product getProductById(Integer id) {
	    Product product = productService.selectByPrimaryKey(id);
	    System.out.println("111" + product);
	    return product;
	}
	
	/**
	 * 更新产品
	 */
	@RequestMapping("/product/update.action")
	@ResponseBody
	public String productUpdate(Product product,Integer id,String name,Integer price) {
		product.setId(id);
        product.setName(name);
        product.setPrice(price);
        System.out.println("222" + product);
	    int rows = productService.updateByPrimaryKeySelective(product);
	    System.out.println(rows);
	    if(rows > 0){
	        return "OK";
	    }else{
	        return "FAIL";
	    }
	}
	/**
	 * 删除产品
	 */
	@RequestMapping("/product/delete.action")
	@ResponseBody
	public String productDelete(Integer id) {
	    int rows = productService.deleteByPrimaryKey(id);
	    if(rows > 0){		
	    	System.out.println("111" + rows);
	    	System.out.println("222" + id);
	        return "OK";
	    }else{
	        return "FAIL";			
	    }
	}
}
